#!/bin/bash

arch="x86"
system="all"
current_pwd=""
package_file=""
packages=""
packages_path=""
grep_depends="Depends"

function error() {
    local date=$(date)
    local para=$1
    echo -e "\033[31m[$date] error : $para \033[0m"
}

function info() {
    local date=$(date)
    local para=$1
    echo -e "\033[32m[$date] info : $para \033[0m"
}

function do_get_language() {
    # 是中文
    if [[ $LANG =~ "zh_CN" ]]; then
        grep_depends="依赖"
    fi
    # 是英文
    if [[ $LANG =~ "en_US" ]]; then
        grep_depends="Depends"
    fi
}

function do_get_system_id() {
    source /etc/os-release
    system="$ID-$VERSION_ID"
}

function do_generate_arch() {
    hostnamectl | grep -i "Architecture: x86"
    if [ $? -ne 0 ]; then
        hostnamectl | grep -i "Architecture: arm"
        if [ $? -ne 0 ]; then
            exit 1
        fi
        arch="arm"
    else
        arch="x86"
    fi
}

function do_configure() {
    current_pwd=$(
        cd "$(dirname "$0")"
        pwd
    )

    do_get_language
    do_generate_arch
    do_get_system_id

    if [ " ${package_file}" == " " ]; then
        package_file=${current_pwd}/package.txt
    fi

    packages_path=${current_pwd}/${arch}/${system}
    mkdir -p ${packages_path}
}

function do_get_depends() {
    ret=$(apt-cache depends $1 | grep $grep_depends | cut -d: -f2 | tr -d "<>")
    echo $ret
}

# 递归获取依赖
function do_get_depends_recursion() {
    i=0
    libs=$1
    while [ $i -lt 3 ]; do
        let i++
        newlist=" "
        for package in $libs; do
            dependen="$(do_get_depends $package)"
            newlist="$newlist $dependen"
            newlist=$(echo $newlist | sed 's/ /\n/g' | sort -u)
        done
        libs=$newlist
    done
    libs=$(echo $libs | sed 's/ /\n/g' | sort -u)
    echo "$libs"
}

function do_make_package_depends() {
    packages="$@"
    for package in $packages; do
        if [ ! -d "${packages_path}/${package}" ]; then
            mkdir -p "${packages_path}/${package}"
        fi
        if [ ! -f ${packages_path}/${package}/${package}.txt ]; then
            info "get ${package} depends ..."
            depends=$(do_get_depends_recursion ${package})
            echo ${package} > ${packages_path}/${package}/${package}.txt
            for depend in $depends; do
                echo ${depend} >> ${packages_path}/${package}/${package}.txt
            done
        fi
    done
}

function do_append_packages() {
    for package in $@; do
        info "append package : ${package}"
        do_make_package_depends ${package}
        if [ $? -ne 0 ]; then
            error "can't download package : ${package}"
        else
            echo "${package}" >>$package_file
        fi
    done
}

function do_sort_packages() {
    sort -u $package_file >$package_file.tmp
    cp $package_file.tmp $package_file
    rm $package_file.tmp
}

main() {
    do_configure
    do_append_packages $@
    do_sort_packages
}

main "$@"